package thread;

import java.util.PriorityQueue;

class MyTimerTask implements Comparable<MyTimerTask>{
    // 要执行的具体任务
    private Runnable runnable;
    // 执行任务的时间戳
    private long time;
    public long getTime(){
        return this.time;
    }
    public MyTimerTask(Runnable runnable, long time){
        this.runnable = runnable;
        this.time = time + System.currentTimeMillis();
    }

    public void run(){
        runnable.run();
    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int)(this.time - o.time);
    }
}

class MyTimer{
    // 需要一个优先级队列，记录要执行的任务，默认是小根堆
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();
    // 锁
    private Object locker = new Object();
    // 定义一个线程，用于扫描优先级队列中的任务
    private Thread t = null;
    // 需要一个构造方法，将任务安排到队列中
    public MyTimer(){
        t = new Thread(() -> {
            try{
                while(!Thread.currentThread().isInterrupted()){
                    synchronized (locker){
                        while(queue.isEmpty()){
                            locker.wait();
                        }
                        MyTimerTask task = queue.peek();
                        long time = task.getTime();
                        long sysTime = System.currentTimeMillis();
                        if(time <= sysTime){
                            task.run();
                            queue.poll();
                        }else{
                            locker.wait(time - sysTime);
                        }
                    }
                }
            }catch(Exception e){
                e.printStackTrace();
            }
        } );

        t.start();
    }
    // 需要一个 schedule() 方法，将任务安排到队列中
    public void schedule(Runnable runnable, long time){
        synchronized (locker){
            MyTimerTask task = new MyTimerTask(runnable, time);
            queue.offer(task);
            locker.notify();
        }
    }

    public void cancel(){
        t.interrupt();
    }
}
public class ThreadDemo27 {
    public static void main(String[] args) throws InterruptedException {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello timer 3000");
            }
        }, 3000);

        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello timer 2000");
            }
        }, 2000);

        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello timer 1000");
            }
        }, 1000);

        Thread.sleep(5000);
        System.out.println("hello main");
        myTimer.cancel();
    }
}
